package com.baozhun.mall.common.widget.dialog

import android.view.View
import androidx.activity.ComponentActivity
import com.alibaba.android.arouter.launcher.ARouter
import com.baozhun.mall.common.R
import com.baozhun.mall.common.arouter.RoutePath
import com.baozhun.mall.common.bindadapter.CustomBindAdapter
import com.baozhun.mall.common.databinding.DialogSkuSelectBinding
import com.baozhun.mall.common.ext.showToast
import com.baozhun.mall.common.listener.ViewOnClickListener
import com.baozhun.mall.common.model.bean.GoodsInfoBean
import com.baozhun.mall.common.model.bean.ImageViewInfo
import com.baozhun.mall.common.model.bean.SkuListItem
import com.baozhun.mall.common.network.mCommonApiService
import com.baozhun.mall.common.util.Constants
import com.baozhun.mall.common.util.VerticalBottomSpan
import com.blankj.utilcode.util.SpanUtils
import com.blankj.utilcode.util.ToastUtils
import com.previewlibrary.GPreviewBuilder
import com.previewlibrary.enitity.IThumbViewInfo
import com.wuhenzhizao.sku.bean.Sku
import com.wuhenzhizao.sku.bean.SkuAttribute
import com.wuhenzhizao.sku.view.OnSkuListener
import me.hgj.jetpackmvvm.base.viewmodel.BaseViewModel
import me.hgj.jetpackmvvm.ext.request


/**
 * @Title：sku选择dialog
 * @Description：
 * @Author：xuefeng.zhu
 * @Since：2022/11/21
 * @Version：1.0.0
 */
class SkuSelectDialog(
    var context: ComponentActivity,
    var goodsInfo: GoodsInfoBean?,
    var viewModel: BaseViewModel?,
    private var selectSkuCallBack: ((skuInfo: String?, sku: Sku?) -> Unit)? = null, //选中sdk回调
) :
    BaseBottomPopupView<DialogSkuSelectBinding>(context), OnSkuListener, ViewOnClickListener {
    private var mSelectSku: Sku? = null
    private var mCurrentSkuImg: String? = null
    override fun getImplLayoutId(): Int {
        return R.layout.dialog_sku_select
    }

    override fun onCreate() {
        super.onCreate()
        mBinding.skuView.setSkuList(transformerSkuData(goodsInfo?.sku_list), this)
        setExchangePriceStyle(goodsInfo?.points_sale_price, goodsInfo?.points_price)
        setImmeExchangePriceStyle(goodsInfo?.points_sale_price, goodsInfo?.points_price)
        mBinding.goodsInfo = goodsInfo
        mCurrentSkuImg = goodsInfo?.goods_cover.toString()
    }

    private fun transformerSkuData(originSkuList: MutableList<SkuListItem>?): MutableList<Sku>? {
        var skuList = arrayListOf<Sku>()
        originSkuList?.forEach { item ->
            var sku = Sku().apply {
                id = item.sku_id
                stockQuantity = item.stock
                mainImage = item.image
                isInStock = item.stock > 0
                originPrice = item.orginal_price
                pointsPrice = item.points_price
                pointsSalePrice = item.points_sale_price
                goodsBuyLimit = item.buy_limit
                sellingPrice = item.price
                attributes = if (item.other.isNullOrEmpty()) {
                    arrayListOf(SkuAttribute(item.color, item.color_value, item.color, item.image, item.image))
                } else {
                    arrayListOf(
                        SkuAttribute(item.color, item.color_value, item.color, item.image, item.image),
                        SkuAttribute(item.other, item.other_value, item.other, item.image, "")
                    )
                }
            }
            skuList.add(sku)
        }
        return skuList
    }

    /**
     *选中时回调，不管选中几个
     */
    override fun onSelect(selectAttribute: SkuAttribute?) {
        mBinding.tvSelectSku.text =
            String.format(context.getString(com.wuhenzhizao.sku.R.string.alr_select_sku_format), mBinding.skuView.arlSelectAttributeName)
        selectSkuCallBack?.invoke(mBinding.skuView.arlSelectAttributeName, mSelectSku)
        CustomBindAdapter.loadImageUrl(mBinding.ivSkuPic, selectAttribute?.skuImage, 12)
    }

    override fun onUnselected(unselectedAttribute: SkuAttribute?) {
        mSelectSku = null
        mCurrentSkuImg = goodsInfo?.goods_cover
        mBinding.tvSelectSku.text =
            String.format(context.getString(com.wuhenzhizao.sku.R.string.alr_select_sku_format), mBinding.skuView.arlSelectAttributeName)
        selectSkuCallBack?.invoke(mBinding.skuView.arlSelectAttributeName, mSelectSku)
        setImmeExchangePriceStyle(goodsInfo?.points_sale_price, goodsInfo?.points_price)
        setExchangePriceStyle(goodsInfo?.points_sale_price, goodsInfo?.points_price)
    }

    /**
     *规格都选中时回调
     */
    override fun onSkuSelected(sku: Sku?) {
        mSelectSku = sku
        mCurrentSkuImg = mSelectSku?.mainImage
        //切换规格重置商品数量
        mBinding.tvGoodsNum.text = "1"
        mBinding.tvSelectSku.text =
            String.format(context.getString(com.wuhenzhizao.sku.R.string.alr_select_sku_format), mBinding.skuView.arlSelectAttributeName)
        selectSkuCallBack?.invoke(mBinding.skuView.arlSelectAttributeName, mSelectSku)
        CustomBindAdapter.loadImageUrl(mBinding.ivSkuPic, mCurrentSkuImg, 12)
        //更新价格信息
//        var currentNum = mBinding.tvGoodsNum.text.toString()
//        viewModel?.request({ mCommonApiService.getGoodsPointInfo(mSelectSku?.id, currentNum.toInt()) }, {
//            setImmeExchangePriceStyle(it.points_sale_price, it.points_price)
//            setExchangePriceStyle(it?.points_sale_price, it?.points_price)
//        }, isShowDialog = false)
        setImmeExchangePriceStyle(mSelectSku?.pointsSalePrice, mSelectSku?.pointsPrice)
        setExchangePriceStyle(mSelectSku?.pointsSalePrice, mSelectSku?.pointsPrice)

    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.close_iv -> {
                dismiss()
            }

            R.id.iv_sku_pic -> {
                GPreviewBuilder.from(context) //activity实例必须
                    .setData(arrayListOf<IThumbViewInfo>(ImageViewInfo(mCurrentSkuImg).apply {
                        mBinding.ivSkuPic.getGlobalVisibleRect(bounds)
                    })) //集合
                    .setCurrentIndex(0)
                    .setType(GPreviewBuilder.IndicatorType.Dot) //指示器类型
                    .start() //启动
            }

            R.id.tv_add -> { //加商品
                checkSelectSku {
                    var currentNum = mBinding.tvGoodsNum.text.toString()
                    var targetNum = currentNum.toInt() + 1
                    if (targetNum <= mSelectSku!!.stockQuantity) {
                        if (targetNum <= mSelectSku!!.goodsBuyLimit) {
                            viewModel?.request({ mCommonApiService.getGoodsPointInfo(mSelectSku?.id, targetNum) }, {
                                mBinding.tvGoodsNum.text = targetNum.toString()
                                updateBtStatus(targetNum)
                                mBinding.tvSub.setImageResource(com.baozhun.mall.res.R.drawable.ic_goods_sub)
                                if (targetNum == mSelectSku!!.goodsBuyLimit)
                                    mBinding.tvAdd.setImageResource(com.baozhun.mall.res.R.drawable.ic_goods_add_unable)
                                setImmeExchangePriceStyle(it.points_sale_price, it.points_price)
                            }, isShowDialog = true)

                        } else {
                            ToastUtils.showShort(com.baozhun.mall.res.R.string.reach_buy_limit)
                            mBinding.tvAdd.setImageResource(com.baozhun.mall.res.R.drawable.ic_goods_add_unable)
                        }
                    } else {
                        ToastUtils.showShort(com.baozhun.mall.res.R.string.goods_stock_out_hint)
                    }
                }

            }

            R.id.tv_sub -> { //减商品
                checkSelectSku {
                    var currentNum = mBinding.tvGoodsNum.text.toString()
                    if (currentNum.toInt() > 1) {
                        var targetNum = currentNum.toInt() - 1
                        viewModel?.request({ mCommonApiService.getGoodsPointInfo(mSelectSku?.id, targetNum) }, {
                            mBinding.tvGoodsNum.text = targetNum.toString()
                            updateBtStatus(targetNum)
                            mBinding.tvAdd.setImageResource(com.baozhun.mall.res.R.drawable.ic_goods_add)
                            if (targetNum == 1)
                                mBinding.tvSub.setImageResource(com.baozhun.mall.res.R.drawable.ic_goods_sub_unable)
                            setImmeExchangePriceStyle(it.points_sale_price, it.points_price)
                        }, isShowDialog = true)
                    } else {
                        ToastUtils.showShort((com.baozhun.mall.res.R.string.reduction_goods_hint))
                        mBinding.tvSub.setImageResource(com.baozhun.mall.res.R.drawable.ic_goods_sub_unable)
                    }
                }
            }

            R.id.tv_imme_exchange -> { //立即兑换
                checkSelectSku {
                    var returnPoints: Double = goodsInfo?.points_price?.toDouble() ?: 0.00
                    ARouter.getInstance().build(RoutePath.Home.CREATE_ORDER)
                        .withString(Constants.Goods.GOODS_SKU, mSelectSku?.id)
                        .withBoolean(Constants.Goods.USE_INTEGRAL, returnPoints > 0)
                        .withInt(Constants.Goods.GOODS_NUM, mBinding.tvGoodsNum.text.toString().toInt())
                        .navigation()
                    dismiss()
                }
            }
        }
    }

    /**
     * 校驗选中的的規格參數
     */
    private fun checkSelectSku(checkSuccess: () -> Unit) {
        if (mSelectSku == null) {
            mBinding.skuView.selectedAttributeList.forEach {
                if (it.value.isEmpty()) {
                    context.showToast(context.getString(com.baozhun.mall.res.R.string.please_choose) + it?.key)
                    return
                }
            }
        } else {
            checkSuccess.invoke()
        }
    }

    /**
     * 更新操作按钮状态
     */
    private fun updateBtStatus(newQuantity: Int) {
        if (mSelectSku == null) {
            mBinding.tvAdd.isEnabled = false
            mBinding.tvSub.isEnabled = false
//            mBinding.goodsNumEt.isEnabled = false
        } else {
            if (newQuantity <= 1) {
                mBinding.tvSub.isEnabled = true
                mBinding.tvAdd.isEnabled = true
            } else if (newQuantity >= mSelectSku!!.stockQuantity) {
                mBinding.tvSub.isEnabled = true
                //超出库存设定位当前最大库存
                mBinding.tvGoodsNum.text = mSelectSku!!.stockQuantity.toString()
//                mBinding.tvAdd.isEnabled = false
            } else {
                mBinding.tvSub.isEnabled = true
                mBinding.tvAdd.isEnabled = true
            }
//            mBinding.goodsNumEt.isEnabled = true
        }
    }

    /**
     * 设置兑换价样式
     */
    private fun setExchangePriceStyle(pointsSalePrice: String?, pointsPrice: String?) {
        //上面样式
        SpanUtils.with(mBinding.tvExchangePrice)
            .append(Constants.Common.MONEY_TAG).setFontSize(13, true).setForegroundColor(context.getColor(com.baozhun.mall.res.R.color.color_FC0503))
            .append(pointsSalePrice?.replace(Constants.Common.MONEY_TAG, "").toString()).setForegroundColor(context.getColor(com.baozhun.mall.res.R.color.color_FC0503)).setSpans(VerticalBottomSpan(21, 3f))
            .append(" + ").setFontSize(13, true).setForegroundColor(context.getColor(com.baozhun.mall.res.R.color.color_333333))
            .append("余额").setFontSize(13, true).setForegroundColor(context.getColor(com.baozhun.mall.res.R.color.color_FC0503))
            .append(pointsPrice.toString()).setForegroundColor(context.getColor(com.baozhun.mall.res.R.color.color_FC0503)).setSpans(VerticalBottomSpan(21, 3f))
            .create()
    }

    /**
     * 更新底部立即兑换样式
     */
    private fun setImmeExchangePriceStyle(pointsSalePrice: String?, pointsPrice: String?) {
        //下面样式
        SpanUtils.with(mBinding.tvImmeExchange)
            .append(Constants.Common.MONEY_TAG).setFontSize(13, true)
            .append(pointsSalePrice?.replace(Constants.Common.MONEY_TAG, "").toString()).setSpans(VerticalBottomSpan(21, 3f))
            .append(" + ").setFontSize(13, true)
            .append("余额").setFontSize(13, true)
            .append(pointsPrice.toString()).setSpans(VerticalBottomSpan(21, 3f))
            .append("  立即兑换").setFontSize(14, true)
            .create()
    }
}